package com.wcity.manage.common.handler;

import com.wcity.manage.common.enums.Code;
import com.wcity.manage.common.exception.CustomException;
import com.wcity.manage.common.utils.Log;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * Created by jn on 2016/11/4.
 *
 */
public class ExceptionHandler implements HandlerExceptionResolver {

    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        Code code = Code.ERROR;
        String message = ex.getMessage();

        if ( ex instanceof CustomException) code = ( (CustomException) ex ).getCode();

        try {
            PrintWriter out = response.getWriter();
            out.print("{\"retCode\":\"");
            out.print(code.getCodeNum());
            out.print("\",\"retDesc\":\"");
            out.print(message);
            out.print("\"}");
        } catch (IOException e) {
            Log.error( ex.getMessage(), e );
        }

        return new ModelAndView();
    }
}
